﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using UnityEditor;
using UnityEngine;
using System.Diagnostics;
using System.Threading;
using System.IO;

public class ThreadableBin2Txt
{
    private float m_sizeThreshold;
    private string m_dataPath;

    private string logData;
    private string errorData;
    public ThreadableBin2Txt(float threshold, string dataPath)
    {
        m_sizeThreshold = threshold;
        m_dataPath = dataPath;
    }
    public string[] ConvertAssetToText(string assetPath, string bin2TxtPath)
    {
        if (!(new FileInfo(assetPath).Length < 1024 * 1024 * m_sizeThreshold))
        {
            return new string[] { };
        }
        var outFileName = Path.GetFileName(assetPath) + ".txt";
        var bin2txtPathWorkingDir = m_dataPath + "/../__tmp/"+ assetPath.GetHashCode();
        if (!Directory.Exists(bin2txtPathWorkingDir))
        {
            Directory.CreateDirectory(bin2txtPathWorkingDir);
        }
        var startInfo = new ProcessStartInfo()
        {
            FileName = bin2TxtPath,
            WorkingDirectory = bin2txtPathWorkingDir,
            Arguments = string.Format(" \"{0}\" \"{1}\"", assetPath, outFileName),
            RedirectStandardOutput = false,
            RedirectStandardError = false,
            UseShellExecute = false,
            CreateNoWindow = true
        };

        var bin2txtProcess = new Process()
        {
            StartInfo = startInfo
        };
        bin2txtProcess.Start();
        bin2txtProcess.WaitForExit();
        UnityEngine.Debug.Log("bin2txtProcess Code :" + bin2txtProcess.ExitCode);
        var outFilePath = bin2txtPathWorkingDir + "/" + outFileName;

        string[] result = null;

        if (File.Exists(outFilePath))
        {
            result = File.ReadAllLines(outFilePath);
            Directory.Delete(bin2txtPathWorkingDir,true);
        }
        else if (bin2txtProcess.ExitCode == 1) 
        {
            result = File.ReadAllLines(assetPath);
        }
        return result;
    }


}

